import { makeDiv, ObjectMapCb } from "../core/utils/utils"
import { getPresitgeTitle } from "../game/defines/presitge_define"
import NpcModules from "../game/npcs/get_npc"
import { getDayTime } from "../game/time";

export default {
  addNpc(isCreate = false){
    if(!this.mapClip || !(this.mapSite || isCreate)){
      this.dialogs.showWarning('警告', '未选中可选的地区放置固有Npc');
      return;
    }

    let data = {
      key: false,
      storeId: this.storeId++,
      peopleAttr: {
        worldPos: this.mapClip.worldPos,
        mapPos: null
      },
      attr: {
        mode: 0
      }
    };

    if(isCreate){
      data.attr.isSave = false;
      data.peopleAttr.mapPos = [];
      data.generate = true;
      data.generateMax = 1;
      data.recoveryDayTime = 0;
    } else {
      data.peopleAttr.mapPos = this.mapSite.mapPos;
    }

    this.mapData.npcs.push(data)

    this.renderAllNpcs();
  },
  editNpc(npc, isCreate = false){
    let btns = ['key:success:Key:unclose', 'presitge:success:声望:unclose', 'mode:success:模式:unclose', 'remove:bad:删除', 'cancel:bad:取消'];

    if(isCreate){
      btns = ['pos:success:定位', 'num:success:数量:unclose', 'day:success:时间:unclose'].concat(btns);
    }

    let npcDialogs = this.dialogs.showInfo('编辑Npc', '对此Npc进行属性操作', 
      btns
    );

    npcDialogs.key.add(() => {
      let { optionSelected } = this.dialogs.showOptionChooser('选择Npc', {
        active: npc.key,
        options: Object.keys(NpcModules).map(key => ({
          value: key,
          text: key,
          desc: ''
        }))
      })

      optionSelected.add(val => {
        npc.key = val;

        this.renderAllNpcs();
      })
    })

    npcDialogs.presitge.add(() => {
      let multipleDialog = this.dialogs.showMultipleItem('编辑声望', {
        items: Object.keys(npc.peopleAttr.presitge || {}).map(key => ({
          pos: key,
          val: npc.peopleAttr.presitge[key]
        })),
        transform: (key, val) => {
          switch(key){
            case 'pos':
              let mapClip = this.getMapClip(val.split(','))
              return mapClip ? mapClip.worldName : '未知'
              break;
            case 'val':
              return getPresitgeTitle(val);
              break;
          }
        },
        confirmDialog: (item) => {
          return new Promise(resolve => {
            let { confirm } = this.dialogs.showOptionInput('声望需求', {
              inputs: [
                {
                  text: '声望',
                  key: 'presitge',
                  value: item ? item.val : 0
                },
              ],
              active: item ? item.pos : false,
              options: this.mapData.world.map(item => ({
                value: item.worldPos.join(','),
                text: item.worldName + `[${item.worldPos}]`,
                desc: ''
              }))
            })

            confirm.add((inputValue, option) => {
              resolve({
                inputValue, option
              })
            })
          })
        }
      })

      multipleDialog.removed.add(data => {
        let presitge = {};
        data.forEach(item => {
          presitge[item.pos] = item.val;
        });
        npc.peopleAttr.presitge = presitge;

        this.renderAllNpcs();
        this.dialogs.showInfo('删除成功', `成功将npc中指定声望删除`);
      })

      multipleDialog.confirm.add((data, item) => {
        if(item){
          let obj = {};
          Object.keys(npc.peopleAttr.presitge).map(key => {
            if(key == item.pos) obj[data.option] = data.inputValue.presitge;
            else obj[key] = npc.peopleAttr[key];
          })
          npc.peopleAttr.presitge = obj;
        } else {
          if(!npc.peopleAttr.presitge) npc.peopleAttr.presitge = {};
          npc.peopleAttr.presitge[data.option] = data.inputValue.presitge;
        }
        this.renderAllNpcs();
      })
    })

    npcDialogs.mode.add(() => {
      let { optionSelected } = this.dialogs.showOptionChooser('选择行为模式', {
        active: npc.attr.mode || '0',
        options: [
          { value: '0', text: '中立', desc: '' },
          { value: '1', text: '敌意', desc: '' },
        ]
      })

      optionSelected.add(val => {
        npc.attr.mode = val;
        this.renderAllNpcs();
      })
    })

    npcDialogs.remove.add(() => {
      let { ok } = this.dialogs.showWarning('警告', '你正在进行删除Npc操作',
        ['cancel:bad:取消', 'ok:success:确认']  
      );

      ok.add(() => {
        this.mapData.npcs = this.mapData.npcs.filter(item => {
          if(item.storeId != npc.storeId) return true;
        })
        this.renderAllNpcs();
      })
    })

    if(isCreate){
      npcDialogs.pos.add(() => {
        this.htmlElement.querySelector('.tip').innerHTML = '已进入长编辑模式';
        this.useMultipleEditMode(() => {
          npc.peopleAttr.mapPos = this.activeMaps.map(item => item.split(','));
          // this.dialogs.showInfo('定位数据', this.activeMaps.join('、'));
          this.renderMapClipNpcs();
        }, npc.peopleAttr.mapPos.map(item => item.join(',')))
      })

      npcDialogs.num.add(() => {
        let { confirm } = this.dialogs.showInput('上限数量', [
          {
            text: '数量',
            key: 'num',
            value: npc.generateMax
          },
        ])

        confirm.add(data => {
          npc.generateMax = data.num;
          this.renderMapClipNpcs();
        })
      })

      npcDialogs.day.add(() => {
        let { confirm } = this.dialogs.showInput('生成时间间隔', [
          {
            text: '时间(day)',
            key: 'day',
            value: npc.recoveryDayTime
          }
        ])

        confirm.add(data => {
          npc.recoveryDayTime = data.day;
          this.renderMapClipNpcs();
        })
      })
    }
  },

  renderAllNpcs(){
    this.renderMapClipNpcs();
    this.renderMapSiteNpcs();
  },
  
  // 绘制所有固有npc
  renderMapSiteNpcs(){
    if(!this.mapSite){
      return;
    }

    let npcs = this.getPosNpcs(this.mapClip.worldPos, this.mapSite.mapPos);
    let npcsParent = this.htmlElement.querySelector('.npc-page .mapSiteNpcs');
    npcsParent.innerHTML = '';

    if(npcs.length > 0){
      npcs.map(item => {
        let presitgeText = [];
        Object.keys(item.peopleAttr.presitge || {}).map(key => {
          let pos = key.split(',');
          presitgeText.push(`${this.getMapClip(pos).worldName}(${getPresitgeTitle(item.peopleAttr.presitge[key])})`);
        })
  
        let dom = makeDiv(npcsParent, '', ['styledButton', 'success', 'mb-1'], `
          <p>ID: ${item.storeId}</p>
          <p>Key: ${item.key}</p>
          <p>声望: ${presitgeText.join('、')}</p>
          <p>模式: ${item.attr.mode == 0 ? '中立' : '敌意'}</p>
        `);

        this.trackClicks(dom, () => {
          this.editNpc(item);
        })
      })
    } else {
      npcsParent.innerHTML = '<p>此地没有固有Npc</p>';
    }
  },

  // 绘制所有动态npc
  renderMapClipNpcs(){
    let npcs = this.getGenerateNpcs(this.mapClip.worldPos);
    let npcsParent = this.htmlElement.querySelector('.create-npc-page .mapSiteNpcs');
    npcsParent.innerHTML = '';

    if(npcs.length > 0){
      npcs.map(item => {
        let presitgeText = [];
        Object.keys(item.peopleAttr.presitge || {}).map(key => {
          let pos = key.split(',');
          presitgeText.push(`${this.getMapClip(pos).worldName}(${getPresitgeTitle(item.peopleAttr.presitge[key])})`);
        })

        let createText = `${item.recoveryDayTime}天(游戏时间) / ${(getDayTime() * item.recoveryDayTime) / 1000}s(现实时间)`;
  
        let dom = makeDiv(npcsParent, '', ['styledButton', 'success', 'mb-1'], `
          <p>ID: ${item.storeId}</p>
          <p>Key: ${item.key}</p>
          <p>声望: ${presitgeText.join('、') || '无'}</p>
          <p>模式: ${item.attr.mode == 0 ? '中立' : '敌意'}</p>
          <p>上限数量: ${item.generateMax}</p>
          <p>刷新时间: ${item.recoveryDayTime <= 0 ? '仅生成一次' : createText}</p>
          <p>放置区域: ${item.peopleAttr.mapPos.map(item => item.join(',')).join('、')}</p>
        `);

        this.trackClicks(dom, () => {
          this.editNpc(item, true);
        })
      })
    } else {
      npcsParent.innerHTML = '<p>此地没有固有Npc</p>';
    }
  },
}